//
//  OneSurpriseColumnVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/11.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh

class OneSurpriseColumnVC: BaseViewController {
    
    var gun = false
    
    var typeId = "-999"
    
    var page = -999
    
    lazy var collectionView : UICollectionView = {
        
        let collet = UICollectionView(frame:CGRect(x: 0, y: 0, width: KScreenW, height: KScreenH - 64), collectionViewLayout: SurpriseFlowLayout())
        
        collet.dataSource = self
        
        collet.delegate = self
        
        collet.contentInset = UIEdgeInsetsMake(ZMTitlesViewH, 0, 49, 0)

        
        collet.backgroundColor = UIColor.viewBgGrey()
        
        collet.register(UINib(nibName: self.StringFromClass(classType: SurpriseCollectionCell.self), bundle: nil), forCellWithReuseIdentifier: SurpriseCollectionCell.identifer())
        
        return collet
    }()
    

    
    var list : [SupriseDataListModel]?
    
    
      override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(collectionView)

        loadData()
        
        weak var weakSelf = self
        
        
        collectionView.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            
            weakSelf?.loadMoreData()
            
        })
        
        
         collectionView.mj_footer.isAutomaticallyHidden = true

             // Do any additional setup after loading the view.
    }
    
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}


extension OneSurpriseColumnVC{
    
    func loadData() {
        
//        if list != nil {
//            
//           collectionView.reloadData()
//            
//            
//            
//        }else{
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["type_id"] = typeId as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=index", parameters: parmeter, completionHandler: { [weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.list = [SupriseDataListModel]()
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self?.list!.append(SupriseDataListModel(dic: dic))
                    
                }
                
                if self!.list?.count == 0{
                
                    self!.showLogoView(text : "暂无抢购商品...")

                
                }
                
                
                let temp = responseObject!["hasmore"] as! String
                
                
                if temp == "0"{
                    
                    self?.collectionView.mj_footer.endRefreshingWithNoMoreData()
                    
                }
                
                self?.collectionView.reloadData()
                
            }else{
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
            
            
        })
        
        
        
        
        
//        }
        
    }
    
    
    
    
    func loadMoreData() {
        
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["type_id"] = typeId as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=index", parameters: parmeter, completionHandler: { [weak self] (responseObject, error) in
            
            
            if error == nil {
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self?.list!.append(SupriseDataListModel(dic: dic))
                    
                }
                
                
                let temp = responseObject!["hasmore"] as! String
                
                if temp == "0" {
                    
                    self?.collectionView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }else{
                    
                    self?.collectionView.mj_footer.endRefreshing()
                    
                }

                
                self?.collectionView.reloadData()
                
            }else{
                
                self!.collectionView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
            
            
        })
        
        

        
        
    }




}


extension OneSurpriseColumnVC : UICollectionViewDataSource,UICollectionViewDelegate{


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        if list == nil {
            return 0
        }

        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if list == nil {
            return 0
        }
        
        return list?.count ?? 0
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SurpriseCollectionCell.identifer(), for: indexPath) as! SurpriseCollectionCell
        
        if list != nil{
            
            if list!.count > indexPath.item {
                
                cell.model = list![indexPath.item]

            }

        }
        
        
        return cell
        
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //通知名称常量
        let NotifyChatMsgRecv = NSNotification.Name(rawValue:"collectionViewItemDidTap")
        
        NotificationCenter.default.post(name: NotifyChatMsgRecv, object: list![indexPath.item])
        
    }
    
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
  
        
//            QL1(scrollView.contentOffset.y);
        
//            QL1(gun);
        if (!gun) {
//                   QL1("888888");
            
            scrollView.contentOffset = CGPoint(x: 0, y: -ZMTitlesViewH)
        }
        
//        QL1(scrollView.contentOffset.y)
        if (scrollView.contentOffset.y <= -ZMTitlesViewH) {
            //        if (!self.fingerIsTouch) {//这里的作用是在手指离开屏幕后也不让显示主视图，具体可以自己看看效果
            //            return;
            //        }
//            QL1("99999999");
            gun = false
            scrollView.contentOffset = CGPoint(x: 0, y: -ZMTitlesViewH)
            
            //通知名称常量
            let NotifyChatMsgRecv = NSNotification.Name(rawValue:"leaveTop")
            
            NotificationCenter.default.post(name: NotifyChatMsgRecv, object: nil)

           
        }
        
    }
    
    



}






class SurpriseFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        itemSize = CGSize(width: (KScreenW - 5) * 0.5, height: (KScreenW - 5) * 0.5)
        minimumLineSpacing = 5
        minimumInteritemSpacing = 5
        sectionInset = UIEdgeInsetsMake(5, 0, 0, 0)
        
        
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        
    }
}
